﻿using Microsoft.AspNetCore.Mvc;
using orm.sqlsugar.api.Entities;
using SqlSugar;

namespace orm.sqlsugar.api.Controllers
{
    /// <summary>
    /// 多表操作（核心是导航属性）
    /// </summary>
    public class MultipleController(ISqlSugarClient sqlSugarClient) 
        : SqlSugarBaseController(sqlSugarClient)
    {
        [HttpPost]
        public async Task<IActionResult> Insert()
        {
            var order = new Order
            {
                Number = DateTime.Now.ToString("yyyyMMddHHmmss"),
                CreateTime = DateTime.Now,
                OrderDetails =
                [
                    new()
                    {
                        ProductName = "导航新增",
                        ProductPrice = 1.1m,
                        CreateTime = DateTime.Now
                    },
                    new()
                    {
                        ProductName = "导航新增2",
                        ProductPrice = 1.1m,
                        CreateTime = DateTime.Now
                    }
                ]
            };

            var result = await SqlSugarClient
                .InsertNav(order)
                .Include(o => o.OrderDetails)
                .ExecuteReturnEntityAsync();

            return Ok("Id：" + result.Id);
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(int id)
        {
            return Ok(await SqlSugarClient
                .DeleteNav<Order>(o => o.Id == id)
                .Include(o => o.OrderDetails)
                .ExecuteCommandAsync());
        }

        [HttpGet]
        public async Task<IActionResult> PageList(int pageIndex, int pageSize)
        {
            RefAsync<int> totalResult = 0;

            var orders = await SqlSugarClient
                .Queryable<Order>()
                .Includes(o => o.OrderDetails)
                .Where(o => o.IsDeleted == false)
                .OrderByDescending(o => o.Id)
                .ToOffsetPageAsync(pageIndex, pageSize, totalResult);

            return Ok(new { rows = orders, total = totalResult.Value });
        }

        [HttpGet]
        public async Task<IActionResult> Detail(int id)
        {
            return Ok(await SqlSugarClient
                .Queryable<Order>()
                .Includes(o => o.OrderDetails)
                .InSingleAsync(id));
        }
    }
}
